﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Timers;
using System.Threading.Tasks;
using System.Net;
using KC.DataAccess.Global;

namespace KC.Business.Scheduler.ScheduledPlugins
{
	public class ResolveDomains : ScheduledPluginBase
	{

		public override void Dispose()
		{
		}
		protected override void CloseInner()
		{
		}
		protected override void FailInner()
		{
		}
		protected async override void RunInner()
		{
			// Build an array of IP rows we can actually enumerate and thus iterate in parallel
			DataTable dt = await SQL.ExecuteDataTable(ConnStr, "select top 100 * from mv8..IPs where domain is null or domain=address order by ID desc");
			Results += dt.Rows.Count.ToString() + " rows selected; ";
			DataRow[] rows = new DataRow[dt.Rows.Count];
			for (int i = 0; i < dt.Rows.Count; i++)
				rows[i] = dt.Rows[i];
			dt.Dispose();

			// Resolve them
			Parallel.ForEach<DataRow>(rows, new ParallelOptions() { MaxDegreeOfParallelism = 8 }, async row => { 
				try {
					IPHostEntry host = Dns.GetHostEntry(row["Address"].ToString());
					if (!string.IsNullOrEmpty(host.HostName))
						await SQL.ExecuteNonQuery(ConnStr, "update IPs set domain='" + host.HostName.Replace("'", "''") + "' where id='" + row["ID"].ToString() + "'");
					else await SQL.ExecuteNonQuery(ConnStr, "update IPs set domain='Unresolvable' where id='" + row["ID"].ToString() + "'"); }
				catch (Exception ex) {
					SQL.ExecuteNonQuery(ConnStr, "Update IPs set domain='Err' where ID='" + row["ID"].ToString() + "'");
					Logging.LogError(ex, ConnStr); } });
		}
		
	}
}
